import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'
import { agencyAsync } from '@/appox/appox'
import { appoxCallback } from '@/appox/appox'

export const useGlobalValuesStore = defineStore('globalValues', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const isEditing = ref(false)
  const parameterKeys = ref([])
  const variableKeys = ref([])
  const selectedParameterId = ref('')
  const selectedVariableId = ref('')
  const parameterValue = ref('')
  const variableValue = ref('')

  // 计算属性
  const canEdit = computed(() => selectedParameterId.value && !isEditing.value)
  const canSave = computed(() => isEditing.value)

  // 动作
  async function initialize() {
    parameterKeys.value = await agencyAsync.getGlobalParameterKeys() || []
    variableKeys.value = await agencyAsync.getGlobalVariableKeys() || []
    
    if (parameterKeys.value.length > 0) {
      selectedParameterId.value = parameterKeys.value[0]
      await updateParameterValue(parameterKeys.value[0])
    }
    
    if (variableKeys.value.length > 0) {
      selectedVariableId.value = variableKeys.value[0]
      await updateVariableValue(variableKeys.value[0])
    }
  }

  async function updateParameterValue(key) {
    if (!key) {
      parameterValue.value = ''
      return
    }

    const value = await agencyAsync.getGlobalParameter(key, '')
    parameterValue.value = formatValue(value || '')
  }

  async function updateVariableValue(key) {
    if (!key) {
      variableValue.value = ''
      return
    }

    let value = await agencyAsync.getGlobalVariable(key, '')
    if (!value) value = ''
    
    // 限制显示长度为100万字符
    if (value.length > 1000000) {
      value = value.substring(0, 1000000)
    }

    variableValue.value = formatValue(value)
  }

  function formatValue(value) {
    // 检查是否为XML格式
    if (value && value.trim().startsWith('<?xml')) {
      try {
        const parser = new DOMParser()
        const xmlDoc = parser.parseFromString(value, "text/xml")
        
        if (!xmlDoc.querySelector('parsererror')) {
          return formatXml(value)
        }
      } catch (e) {
        console.warn('XML解析失败:', e)
      }
    }
    
    return value
  }

  function formatXml(xml) {
    try {
      const parser = new DOMParser()
      const doc = parser.parseFromString(xml, "text/xml")
      
      if (doc.querySelector('parsererror')) {
        return xml
      }

      // 提取XML声明
      let declaration = ''
      if (xml.startsWith('<?xml')) {
        const endIndex = xml.indexOf('?>') + 2
        declaration = xml.substring(0, endIndex) + '\n'
      }
      
      function formatNode(node, indent) {
        const tab = '  '
        let result = ''
        
        if (node.nodeType === Node.ELEMENT_NODE) {
          result += indent + '<' + node.nodeName
          
          const attributes = Array.from(node.attributes)
          if (attributes.length > 0) {
            for (const attr of attributes) {
              result += '\n' + indent + tab + attr.name + '="' + attr.value + '"'
            }
            result += '\n' + indent
          }
          
          const childNodes = Array.from(node.childNodes)
          if (childNodes.length === 0) {
            result += '/>\n'
          } else {
            result += '>\n'
            
            for (const child of childNodes) {
              result += formatNode(child, indent + tab)
            }
            
            result += indent + '</' + node.nodeName + '>\n'
          }
        }
        else if (node.nodeType === Node.TEXT_NODE) {
          const text = node.textContent.trim()
          if (text) {
            result += indent + text + '\n'
          }
        }
        else if (node.nodeType === Node.COMMENT_NODE) {
          result += indent + '<!--' + node.textContent + '-->\n'
        }
        
        return result
      }
      
      return declaration + formatNode(doc.documentElement, '')
    } catch (e) {
      console.warn('XML格式化失败:', e)
      return xml
    }
  }

  async function handleParameterSelect(key) {
    selectedParameterId.value = key
    await updateParameterValue(key)
  }

  async function handleVariableSelect(key) {
    selectedVariableId.value = key
    await updateVariableValue(key)
  }

  function startEditing() {
    isEditing.value = true
  }

  async function saveParameter() {
    if (selectedParameterId.value) {
      let value = parameterValue.value
      // 移除所有回车和空格缩进
      value = value.replace(/\s+/g, ' ').trim()
      await agencyAsync.setGlobalParameter(selectedParameterId.value, value)
      isEditing.value = false
      await updateParameterValue(selectedParameterId.value)
    }
  }

  function show() {
    return dialogQueue.show({
      onLoaded: () => initialize()
    })
  }

  function hide() {
    dialogQueue.hide()
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    isEditing,
    parameterKeys,
    variableKeys,
    selectedParameterId,
    selectedVariableId,
    parameterValue,
    variableValue,
    // 计算属性
    canEdit,
    canSave,
    // 动作
    initialize,
    handleParameterSelect,
    handleVariableSelect,
    startEditing,
    saveParameter,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 